<template>
  <div style="padding: 20px;">
    <Row>
      <i-col span="24">
        <Input placeholder="搜索商品名称" v-model="searchName" style="width: 150px;margin-bottom: 10px" />
        <Button style="margin: 0 10px 10px 0;" type="primary" @click="searchShop">搜索</Button>
        <Button style="margin: 0 10px 10px 0;float: right;" type="primary" @click="addShop">添加商品</Button>
      </i-col>
      <i-col span="24">
        <Table border :columns="goodsTitle" :data="goodsList"></Table>
        <Page :total="total" show-elevator @on-change="pageChange" style="text-align:right;margin-top: 15px;"/>
      </i-col>
    </Row>
    <Modal v-model="add_shop" :title="title" :width="750" @on-ok="sbtShop(title)" @on-cancel="empty" :mask-closable="false">
      <Form :model="addForm" :label-width="80">
        <FormItem label="商品名称">
          <Input v-model="addForm.goodsName" placeholder="请输入商品名称" />
        </FormItem>
        <FormItem label="商品价格">
          <InputNumber :max="100000" :min="1" v-model="addForm.goodsPrice"></InputNumber>
        </FormItem>
        <FormItem label="商品描述">
          <Input v-model="addForm.goodsBrief" type="textarea" :autosize="{minRows: 3,maxRows: 5}" placeholder="请输入商品描述" />
        </FormItem>
        <FormItem label="商品库存" prop="participate">
          <InputNumber :max="10000" :min="1" v-model="addForm.goodsNum"></InputNumber>
        </FormItem>
        <FormItem label="商品图片">
          <div class="demo-upload-list" v-for="item in uploadList">
            <template v-if="item.status === 'finished'">
              <img :src="item.url">
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload
            ref="upload"
            :show-upload-list="false"
            :on-success="handleSuccess"
            :format="['jpg','jpeg','png']"
            :before-upload="handleBeforeUpload"
            multiple
            type="drag"
            accept="image/*"
            action="//47.97.110.121:8080/miniApi/picture/uploadOne"
            style="display: inline-block;width:58px;">
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <Modal title="查看大图" v-model="visible">
            <img :src="imgName" v-if="visible" style="width: 100%">
          </Modal>
        </FormItem>
        <FormItem label="商品分类">
          <Select v-model="addForm.typeId">
            <Option v-for="item in typeList" :value="item.typeId" :key="item.typeId">{{item.typeName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="商品品牌">
          <Select v-model="addForm.brandId">
            <Option v-for="item in brandList" :value="item.brandId" :key="item.brandId">{{item.brandName}}</Option>
          </Select>
        </FormItem>
        <FormItem label="设置禁启">
          <i-switch size="large" v-model="addForm.goodsStatus"  @on-change.self="StatusChange">
            <span slot="open">下架</span>
            <span slot="close">上架</span>
          </i-switch>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
  import {formatDate} from '@/config/date'
  export default {
    name: 'goodsList',
    data () {
      return {
        add_shop: false,
        title: '',
        number: 0,
        total: 0,
        searchName: '',
        pic: [],
        imgName: '',
        visible: false,
        uploadList: [],
        addForm: {
          goodsName: '',
          goodsImg: '',
          goodsPrice: 1,
          goodsNum: 1,
          goodsBrief: '',
          typeId: [],
          brandId: [],
          goodsStatus: true
        },
        goodsTitle: [
          {
            title: '商品编号',
            align: 'center',
            key: 'goodsShowId',
            tooltip: true
          },
          {
            title: '商品名称',
            align: 'center',
            key: 'goodsName',
            tooltip: true
          },
          {
            title: '商品价格',
            align: 'center',
            tooltip: true,
            key: 'goodsPrice'
          },
          {
            title: '商品描述',
            tooltip: true,
            align: 'center',
            key: 'goodsBrief'
          },
          {
            title: '添加时间',
            tooltip: true,
            align: 'center',
            key: 'goodsAddedTime',
            render: (h, params) => {
              return h('div', formatDate(new Date(params.row.goodsAddedTime), 'yyyy-MM-dd hh:mm')
              )
            }
          },
          {
            title: '修改时间',
            tooltip: true,
            align: 'center',
            key: 'goodsUpdateTime',
            render: (h, params) => {
              return h('div', formatDate(new Date(params.row.goodsUpdateTime), 'yyyy-MM-dd hh:mm')
              )
            }
          },
          {
            title: '商品品牌',
            align: 'center',
            tooltip: true,
            key: 'brandName'
          },
          {
            title: '商品分类',
            align: 'center',
            tooltip: true,
            key: 'typeName'
          },
          {
            title: '状态',
            align: 'center',
            render: (h, params) => {
              const row = params.row
              const color = row.goodsStatus === 1 ? 'primary' : row.goodsStatus === 0 ? 'error' : ''
              const text = row.goodsStatus === 1 ? '下架' : row.goodsStatus === 0 ? '上架' : ''
              return h('Tag', {
                props: {
                  type: 'dot',
                  color: color
                }
              }, text)
            }
          },
          {
            title: '操作',
            key: 'action',
            width: 250,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.editorShow()
                      this.addForm.goodsName = params.row.goodsName
                      this.pic = params.row.goodsImg
                      this.imageUrl(params.row.goodsImg)
                      this.addForm.goodsNum = params.row.goodsNum
                      this.addForm.goodsPrice = params.row.goodsPrice
                      this.addForm.goodsBrief = params.row.goodsBrief
                      this.addForm.typeId = params.row.typeId
                      this.addForm.brandId = params.row.brandId
                      this.addForm.goodsId = params.row.goodsId
                      if (params.row.goodsStatus === 1) {
                        this.addForm.goodsStatus = true
                      } else {
                        this.addForm.goodsStatus = false
                      }
                    }
                  }
                }, '编辑'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '你确定删除该商品吗？',
                        okText: '确定',
                        cancelText: '取消',
                        onOk: () => {
                          this.removeGoods()
                        }
                      })
                    }
                  }
                }, '删除')
              ])
            }
          }
        ],
        goodsList: [],
        typeList: [],
        brandList: []
      }
    },
    mounted () {
      this._typeList()
      this._brandList()
      this._goodsList(this.number)
    },
    methods: {
      _typeList () {
        let url = '/api/goods/type/list'
        this.$get(url).then((res) => {
          if (res.code === 200) {
            this.typeList = res.data
          }
        })
      },
      _brandList () {
        let url = '/api/goods/brand/list'
        this.$get(url).then((res) => {
          if (res.code === 200) {
            this.brandList = res.data
          }
        })
      },
      _goodsList (number) {
        let url = '/api/goods/product/page'
        let from = {
          goodsName: this.searchName,
          pageSize: 10,
          pageNumber: number
        }
        this.$get(url, from).then((res) => {
          if (res.code === 200) {
            this.goodsList = res.data.list
            this.total = res.data.total
          }
        })
      },
      showModel (title) {
        this.add_shop = true
        this.title = title
      },
      addShop () {
        this.showModel('添加商品')
      },
      editorShow () {
        this.showModel('编辑商品')
      },
      StatusChange (status) {
        this.addForm.goodsStatus = status
      },
      sbtShop (title) {
        if (title === '添加商品') {
          this.Add()
        } else {
          this.submitEdit()
        }
      },
      Add () {
        let url = '/api/goods/product/add'
        let from = {
          goodsName: this.addForm.goodsName,
          goodsImg: this.pic,
          goodsPrice: this.addForm.goodsPrice,
          goodsNum: this.addForm.goodsNum,
          goodsBrief: this.addForm.goodsBrief,
          typeId: this.addForm.typeId,
          brandId: this.addForm.brandId,
          goodsStatus: Number(this.addForm.goodsStatus)
        }
        this.$post(url, from).then((res) => {
          if (res.code === 200) {
            this.$Message.success('添加成功')
            this._goodsList(this.number)
            this.empty()
          } else {
            this.$Message.error('添加失败')
          }
        })
      },
      submitEdit () {
        let url = '/api/goods/product/update'
        let from = {
          goodsName: this.addForm.goodsName,
          goodsImg: this.pic,
          goodsPrice: this.addForm.goodsPrice,
          goodsNum: this.addForm.goodsNum,
          goodsBrief: this.addForm.goodsBrief,
          typeId: this.addForm.typeId,
          brandId: this.addForm.brandId,
          goodsId: this.addForm.goodsId,
          goodsStatus: Number(this.addForm.goodsStatus)
        }
        this.$put(url, from).then((res) => {
          if (res.code === 200) {
            this.$Message.success('修改成功')
            this._goodsList(this.number)
            this.empty()
          } else {
            this.$Message.error('修改失败')
          }
        })
      },
      searchShop () {
        if (!this.searchStoreName) {
          this.$Message.warning('请输入查询条件')
          return
        }
        this._goodsList(this.number)
      },
      removeGoods (id) {
        let url = 'goods/product/delete'
        let from = {
          goodsId: id
        }
        this.$deletes(url, from).then((res) => {
          if (res.code === 200) {
            console.log(res)
            this.$Message.success('删除成功')
            this._goodsList(this.number)
          } else {
            this.$Message.error('删除失败')
          }
        })
      },
      pageChange (change) {
        let number = change
        this.number = number
        this._goodsList(number)
      },
      empty () {
        this.addForm = {}
        this.pic = []
        this.uploadList = []
        this.addForm.goodsStatus = true
      },
      handleView (url) {
        this.imgName = url
        this.visible = true
      },
      handleRemove (file) {
        const fileList = this.$refs.upload.fileList
        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1)
        let url = '/api/miniApi/picture/delete'
        let fileUrl = {
          fileUrl: file.url
        }
        this.$deletes(url, fileUrl).then((res) => {
          if (res.code === 200) {
            this.pic.splice(this.pic.indexOf(file), 1)
            this.uploadList.splice(this.uploadList.indexOf(file), 1)
            this.$Message.success('删除成功')
          } else {
            this.$Message.error('删除失败')
          }
        })
      },
      handleSuccess (res, file) {
        file.url = file.response.data
        this.$Message.success('上传成功')
        this.pic.push(file.response.msg)
        console.log(this.pic)
        let url = file
        url.url = url.response.msg
        this.uploadList.push(url)
      },
      handleBeforeUpload () {
        const check = this.uploadList.length < 9
        if (!check) {
          this.$Message.error('最多上传9张图片')
        }
        return check
      },
      show (e) {
        this.imgName = e.target.src
        this.visible = true
      },
      imageUrl(url) {
        let arr = []
        for (let i = 0; i < url.length; i++) {
          let obj = {}
          obj.url = url[i]
          obj.status = 'finished'
          arr.push(obj)
          this.uploadList = arr
        }
      }
    }
  }
</script>

<style scoped>
  .ivu-row {
    margin-left: 0px !important;
    margin-right: 0px !important;
  }
  .selector .ivu-row ivu-col-span-8{
    margin-left: 0px !important;
    margin-right: 0px !important;
    width: 33% !important;
  }
  .demo-upload-list{
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
    margin-right: 4px;
  }
  .demo-upload-list img{
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover{
    display: block;
  }
  .demo-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
</style>
